package com.xnew.validate;

import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.Range;

/**
 * 例子
 *  @NotNull(message="登录名称不能为空")
    @NotBlank(message="登录密码不能为空")
    @Range(min=0,max=1,message="状态值必须在0-1之间")
    @Min(value=100, message="值必须是数字并且大于等于100")
    @Max(value=100, message="值必须是数字并且大于等于100")
    @Email(message="邮箱地址不符合规则")
    @Length(min=12,max=24,message="字符串长度允许方位12至24")
    @Pattern(regexp="^((13[0-9])|(14[579])|(15([0-3,5-9]))|(16[6])|(17[0135678])|(18[0-9]|19[89]))\\d{8}$",message="手机号码必须符合规则") 
 * */
public class BeanValidate {
	
	/**
	 * 对传入的bean进行校验
	 * @return success 校验通过
	 * @return error 校验失败
	 * */
	public static String FormBeanValidate(Object beanObject, String... includeField){
		String returnValie = null;
		Field[] fields = beanObject.getClass().getDeclaredFields();
    	//对所有属性设置访问权限  当类中的成员变量为private时 必须设置此项
    	AccessibleObject.setAccessible(fields, true);
    	if(null == includeField || includeField.length ==0){
    		for(int i=0;i<fields.length;i++){
    			returnValie = validateField(beanObject, fields[i], fields[i].getName());
    			if(!"success".equals(returnValie)){
    				return returnValie;
    			}
    		}
    	}else{
    		Field field = null;
    		for(int i=0;i<includeField.length;i++){
    			try {
					field = beanObject.getClass().getDeclaredField(includeField[i]);
					returnValie = validateField(beanObject, field, field.getName());
					if(!"success".equals(returnValie)){
	    				return returnValie;
	    			}
				} catch (Exception e) {
					e.printStackTrace();
				}
    		}
    	}
		return "success";
	}
	
	/**
	 * 根据对象内属性进行校验
	 * @return success 校验通过
	 * @return error 校验失败
	 * */
	public static String validateField(Object beanObject, Field field, String fieldName){
		if("serialVersionUID".equals(fieldName)){
			return "success";
		}
		String returnValie = null;
		Object value = getFieldValueByName(beanObject, fieldName);//通过反射获取属性值
		Annotation[] annotations = field.getAnnotations();
		if(null != annotations && annotations.length !=0){
			for(int i=0;i<annotations.length;i++){
				if(null != annotations[i].annotationType()){
					if(annotations[i].annotationType().toString().indexOf("NotNull") >= 0){
						NotNull notNull = field.getAnnotation(NotNull.class);
			    		if(notNull != null){
			    			returnValie = validateFieldNotNull(value, notNull.message());
			    			if(!"success".equals(returnValie)){
			    				return returnValie;
			    			}
			    		}
					}
					if(annotations[i].annotationType().toString().indexOf("NotBlank") >= 0){
						NotBlank notBlank = field.getAnnotation(NotBlank.class);
			    		if(notBlank != null){
			    			returnValie = validateFieldNotBlank(value, notBlank.message());
			    			if(!"success".equals(returnValie)){
			    				return returnValie;
			    			}
			    		}
					}
					if(annotations[i].annotationType().toString().indexOf("Range") >= 0){
						Range range = field.getAnnotation(Range.class);
			    		if(range != null){
			    			returnValie = validateFieldRange(value, range.min(), range.max(), range.message());
			    			if(!"success".equals(returnValie)){
			    				return returnValie;
			    			}
			    		}
					}
					if(annotations[i].annotationType().toString().indexOf("Min") >= 0){
						Min min = field.getAnnotation(Min.class);
			    		if(min != null){
			    			returnValie = validateFieldMin(value, min.value(), min.message());
			    			if(!"success".equals(returnValie)){
			    				return returnValie;
			    			}
			    		}
					}
					if(annotations[i].annotationType().toString().indexOf("Max") >= 0){
						Max max = field.getAnnotation(Max.class);
			    		if(max != null){
			    			returnValie = validateFieldMax(value, max.value(), max.message());
			    			if(!"success".equals(returnValie)){
			    				return returnValie;
			    			}
			    		}
					}
					if(annotations[i].annotationType().toString().indexOf("Email") >= 0){
						Email email = field.getAnnotation(Email.class);
			    		if(email != null){
			    			returnValie = validateFieldEmail(value, email.message());
			    			if(!"success".equals(returnValie)){
			    				return returnValie;
			    			}
			    		}
					}
					if(annotations[i].annotationType().toString().indexOf("Length") >= 0){
						Length length = field.getAnnotation(Length.class);
			    		if(length != null){
			    			returnValie = validateFieldLength(value, length.min(), length.max(), length.message());
			    			if(!"success".equals(returnValie)){
			    				return returnValie;
			    			}
			    		}
					}
					if(annotations[i].annotationType().toString().indexOf("Pattern") >= 0){
						javax.validation.constraints.Pattern pattern = field.getAnnotation(javax.validation.constraints.Pattern.class);
			    		if(pattern != null){
			    			returnValie = validateFieldPattern(value, pattern.regexp(), pattern.message());
			    			if(!"success".equals(returnValie)){
			    				return returnValie;
			    			}
			    		}
					}
				}
			}
		}		
		return "success";
	}
	
	/**
	 * 通过对象与属性反射获取值
	 * */
	public static Object getFieldValueByName(Object o, String fieldName) {  
		try {    
			String firstLetter = fieldName.substring(0, 1).toUpperCase();    
			String getter = "get" + firstLetter + fieldName.substring(1);    
			Method method = o.getClass().getMethod(getter, new Class[] {});    
			Object value = method.invoke(o, new Object[] {});    
			return value;    
		} catch (Exception e) {    
			e.printStackTrace();
			return null;    
		}    
	}
	
	/**
	 * 手机号码校验
	 * @return success 校验通过
	 * @return error 校验失败
	 * */
	public static String validatePhone(String phone){
		if(null == phone || "".equals(phone)){
			return "success";
		}
		String regex = "^(1[3-9])\\d{9}$";
		if(phone.length() != 11){
			return "error";
		}else{
			Pattern pattern = Pattern.compile(regex);
			Matcher matcher = pattern.matcher(phone);
			boolean isMatch = matcher.matches();
			if(isMatch){
				return "success";
			} else {
				return "error";
			}
		}
	}
	
	/**
	 * 电话号码校验
	 * @return success 校验通过
	 * @return error 校验失败
	 * */
	public static String validateTelePhone(String phone){
		if(null == phone || "".equals(phone)){
			return "success";
		}
		String regex = "^[0][0-9]{2,3}-[0-9]{5,10}$";
		if(phone.length() != 12 && phone.length() != 13){
			return "error";
		}else{
			Pattern pattern = Pattern.compile(regex);
			Matcher matcher = pattern.matcher(phone);
			boolean isMatch = matcher.matches();
			if(isMatch){
				return "success";
			} else {
				return "error";
			}
		}
	}
	
	/**
	 * NotNull校验
	 * @return success 校验通过
	 * @return error 校验失败
	 * */
	public static String validateFieldNotNull(Object value, String... message){
		if(null == value || "".equals(value.toString()) || "".equals(value.toString().trim())){
			if(null != message && message.length !=0){
				return message[0];
			}
			return "error";
		}
		return "success";
	}
	
	/**
	 * NotBlank校验
	 * @return success 校验通过
	 * @return error 校验失败
	 * */
	public static String validateFieldNotBlank(Object value, String... message){
		if(null == value || "".equals(value.toString()) || "".equals(value.toString().trim())){
			if(null != message && message.length !=0){
				return message[0];
			}
			return "error";
		}
		return "success";
	}
	
	/**
	 * Range取值范围校验
	 * @return success 校验通过
	 * @return error 校验失败
	 * */
	public static String validateFieldRange(Object value, long minValue, long maxValue, String... message){
		if(null == value || "".equals(value.toString())){
			return "success";
		}
		if(Long.parseLong(value.toString()) < minValue || Long.parseLong(value.toString()) > maxValue){
			if(null != message && message.length !=0){
				return message[0];
			}
			return "error";
		}
		return "success";
	}
	
	/**
	 * Min取值范围校验
	 * @return success 校验通过
	 * @return error 校验失败
	 * */
	public static String validateFieldMin(Object value, double minValue, String... message){
		if(null == value || "".equals(value.toString())){
			return "success";
		}
		if(Double.parseDouble(value.toString()) < minValue){
			if(null != message && message.length !=0){
				return message[0];
			}
			return "error";
		}
		return "success";
	}
	
	/**
	 * Max取值范围校验
	 * @return success 校验通过
	 * @return error 校验失败
	 * */
	public static String validateFieldMax(Object value, double maxValue, String... message){
		if(null == value || "".equals(value.toString())){
			return "success";
		}
		if(Double.parseDouble(value.toString()) > maxValue){
			if(null != message && message.length !=0){
				return message[0];
			}
			return "error";
		}
		return "success";
	}
	
	/**
	 * Email校验
	 * @return success 校验通过
	 * @return error 校验失败
	 * */
	public static String validateFieldEmail(Object email, String... message){
		if(null == email || "".equals(email.toString())){
			return "success";
		}
		Pattern pattern =  Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//复杂匹配  
        Matcher matcher = pattern.matcher(email.toString());  
        if(!matcher.matches()){
			if(null != message && message.length !=0){
				return message[0];
			}
			return "error";
		}
		return "success";
	}
	
	/**
	 * Length校验
	 * @return success 校验通过
	 * @return error 校验失败
	 * */
	public static String validateFieldLength(Object value, int minLength, int maxLength, String... message){
		if(null == value || "".equals(value.toString())){
			return "success";
		}
        if(value.toString().length() < minLength || value.toString().length() > maxLength){
			if(null != message && message.length !=0){
				return message[0];
			}
			return "error";
		}
		return "success";
	}
	
	/**
	 * Pattern正则表达式校验
	 * @return success 校验通过
	 * @return error 校验失败
	 * */
	public static String validateFieldPattern(Object value, String patternStr, String... message){
		if(null == value || "".equals(value.toString())){
			return "success";
		}
		Pattern pattern =  Pattern.compile(patternStr);//复杂匹配  
        Matcher matcher = pattern.matcher(value.toString());  
        if(!matcher.matches()){
			if(null != message && message.length !=0){
				return message[0];
			}
			return "error";
		}
		return "success";
	}

}
